//
//  UITextView+OSCEmoticon.m
//  OSChina
//
//  Created by 8b410-2 on 17/1/7.
//  Copyright © 2017年 abb. All rights reserved.
//

#import "UITextView+OSCEmoticon.h"

@implementation UITextView (OSCEmoticon)

- (void)insertEmoticon:(OSCEmoticon *)emoticon font:(UIFont *)font {
    
    // 判断是否是删除按钮
    if (emoticon.isRemoveButton) {
        [self deleteBackward];
    }
    // 判断是否是图片表情
    if (emoticon.imageName) {
        // 获取原文本的属性文本
        NSMutableAttributedString *strM = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedText];
        // 创建附件
        NSAttributedString *textImage = [OSCEmoticonAttachment getEmoticonAttachmentWithEmoticon:emoticon fontSize:font.pointSize];
        // 获取光标位置
        NSRange range = self.selectedRange;
        // 插入带附件的属性字符串
        [strM replaceCharactersInRange:range withAttributedString:textImage];
        // 设置属性文本的字体
        [strM addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, strM.length)];
        // 替换原文的属性文本
        self.attributedText = strM;
        // 恢复光标
        self.selectedRange = NSMakeRange(range.location + 1, 0);
        // 手动触发代理
        if ([self.delegate respondsToSelector:@selector(textViewDidChange:)]) {
            [self.delegate textViewDidChange:self];
        }
    }
}

- (NSString *)stringFromEmoticonAttributedWithType:(OSCEmoticonStringType)type {
    
    __block NSString *strM = @"";
    /// 枚举当前的属性字符串
    [self.attributedText enumerateAttributesInRange:NSMakeRange(0, self.attributedText.length) options:0 usingBlock:^(NSDictionary<NSString *,id> * _Nonnull attrs, NSRange range, BOOL * _Nonnull stop) {
       
        // 判断是否有附件
        NSString *attachmentKey = @"NSAttachment";
        if ([attrs valueForKey:attachmentKey]) {
            // 拿到附件的文字属性 拼接到后面
            OSCEmoticonAttachment *attachment = [attrs valueForKey:attachmentKey];
            // TODO: - 尝试用表情的 图片名字 去替换字符串,仍不能解决动弹列表表情显示对不上号的问题
            //         目前只有动弹评论可以使用表情名字(chs) 显示正确的表情
            switch (type) {
                case OSCEmoticonStringTypeChs:
                    strM = [strM stringByAppendingString:attachment.chs];
                    break;
                case OSCEmoticonStringTypeImageName:
                    strM = [strM stringByAppendingString:[NSString stringWithFormat:@"[%ld]",attachment.num]];
                    break;
            }
        } else {
            // 拼接文字
            strM = [strM stringByAppendingString:[self.text substringWithRange:range]];
        }
    }];
    return strM;
}

@end
